using Godot;
using System;

public partial class Player : Area2D
{
	[Signal]
public delegate void HitEventHandler();

	[Export]
	public int Speed {get;set;}=400;
	public Vector2 ScreenSize;
	
	//当节点进入场景树时调用
	public override void _Ready(){
		ScreenSize = GetViewportRect().Size;
		Hide();
	}
	//在每一帧都被调用
	public override void _Process(double delta){
		var velocity = Vector2.Zero; // The player's movement vector.

		if (Input.IsActionPressed("move_right"))
		{
				velocity.X += 1;
		}

		if (Input.IsActionPressed("move_left"))
		{
				velocity.X -= 1;
		}

		if (Input.IsActionPressed("move_down"))
		{
				velocity.Y += 1;
		}

		if (Input.IsActionPressed("move_up"))
		{
		velocity.Y -= 1;
	}

	var animatedSprite2D = GetNode<AnimatedSprite2D>("AnimatedSprite2D");

	if (velocity.Length() > 0)
	{
		velocity = velocity.Normalized() * Speed;
		animatedSprite2D.Play();
	}
	else
	{
		animatedSprite2D.Stop();
	}
	//防止离开屏幕
	Position += velocity * (float)delta;
	Position = new Vector2(
	x: Mathf.Clamp(Position.X, 0, ScreenSize.X),
	y: Mathf.Clamp(Position.Y, 0, ScreenSize.Y)
);

if (velocity.X != 0)
{
	animatedSprite2D.Animation = "walk";
	animatedSprite2D.FlipV = false;
	// See the note below about the following boolean assignment.
	animatedSprite2D.FlipH = velocity.X < 0;
}
else if (velocity.Y != 0)
{
	animatedSprite2D.Animation = "up";
	animatedSprite2D.FlipV = velocity.Y > 0;
}
	}
	
	private void OnBodyEntered(Node2D body)
{
	Hide(); // 玩家在碰撞后消失
	EmitSignal(SignalName.Hit);//触发碰撞信号
	// 敌人每次击中 玩家时都会发出一个信号。我们需要禁用玩家的碰撞检测，确保我们不会多次触发 hit 信号
	GetNode<CollisionShape2D>("CollisionShape2D").SetDeferred(CollisionShape2D.PropertyName.Disabled, true);
}

public void Start(Vector2 position)
{
	Position = position;//设置位置
	Show();//显示
	GetNode<CollisionShape2D>("CollisionShape2D").Disabled = false;
}

}
